package com.zhajh.activity;

import org.apache.mina.core.buffer.IoBuffer;
import org.json.JSONException;
import org.json.JSONObject;

import com.zhajh.MyApp;
import com.zhajh.R;
import com.zhajh.socket.ClientHandler;
import com.zhajh.socket.SocketClient;
import com.zhajh.utils.Const;
import com.zhajh.utils.ToastUtil;
import com.zhajh.view.GameView;
import com.zhajh.view.MyWaitDialog;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

/******************************************
 * 登录 -> 找桌子 -> 发牌
 ******************************************/

public class MainActivity extends Activity implements ClientHandler.MsgCallback, View.OnClickListener
{
	private static final String HOST = "192.168.1.149";///这个地址根据服务端地址设置
	private static final int PORT = 8888;

	TextView m_TextView = null;
	Context mContext;
	SocketClient mSocketClient = null;
	GameView mGameView = null;
	View mReadyView = null;

	private static final int STEP_NULL = 0;
	private static final int STEP_LOGON = 1;
    private static final int STEP_FIND_TABLE = 2;
    private static final int STEP_READY = 3;

    private int mStep = 0;
    //private String mUsername = "wsh";	// "wsh"
    //private String mPasswd = "sunny";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mContext = this;

        //SystemClock.sleep(10);

        setContentView(R.layout.activity_main);
        mGameView = (GameView)findViewById(R.id.game_view);
        mReadyView = (View)findViewById(R.id.layout_ready);
        mSocketClient = new SocketClient();
        mSocketClient.setMsgCallback(this);
        findViewById(R.id.btn_change_table).setOnClickListener(this);
        findViewById(R.id.btn_start).setOnClickListener(this);

        // logon
        startLogon();
    }

    @Override
    public void onStop()
    {
    	super.onStop();
    }

    @Override
    public void onDestroy()
    {
    	if (mSocketClient != null)
    	{
    		mSocketClient.closeSocket();
    		mSocketClient = null;
    	}

    	super.onDestroy();
    }

    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
    	//Log.d(TAG, "onKeyDown: "+event);
    	return super.onKeyDown(keyCode, event);
    }

    public boolean onKeyUp(int keyCode, KeyEvent event)
    {
    	//Log.d(TAG, "onKeyUp: "+event);
    	return super.onKeyUp(keyCode, event);
    }

	private class ServerTask extends AsyncTask<Void, Void, JSONObject> {
		MyWaitDialog mWaitDialog = null;

		@Override
		protected void onPreExecute() {
            super.onPreExecute();

            int title = R.string.wait_title;
            int msg = 0;

            switch (mStep)
            {
            case STEP_LOGON:
            	msg = R.string.logoning;
            	break;

            case STEP_FIND_TABLE:
            	msg = R.string.find_table;
            	break;

            default:
            	break;
            }

            if (msg != 0)
            {
            	mWaitDialog = new MyWaitDialog(MainActivity.this, title, msg);
            	mWaitDialog.show();
            }
		}

		@Override
		protected JSONObject doInBackground(Void... params) {
			switch (mStep)
            {
            case STEP_LOGON:
                if (!mSocketClient.connect(HOST, PORT))
                {
                	// 连接超时
                	return null;
                }

                String deviceID = MyApp.getAndroidDeviceID();
		        String model = Build.MODEL;
		        String username = MyApp.sUserName;
		        String passwd = MyApp.sUserPasswd;

                return mSocketClient.logon(username, passwd, deviceID, model);

            case STEP_FIND_TABLE:
            	return mSocketClient.findTable();

            default:
            	break;
            }

			return null;
		}

		@Override
		protected void onPostExecute(JSONObject result) {
			if(mWaitDialog!=null){
				mWaitDialog.dismiss();
			}

            switch (mStep)
            {
            case STEP_LOGON:
            	procLogonResult(result);
            	break;

            case STEP_FIND_TABLE:
            	procFindTableResult(result);
            	break;

            default:
            		break;
            }

			super.onPostExecute(result);
		}
	}

	private void startLogon()
	{
        mStep = STEP_LOGON;
        new ServerTask().execute();
	}

	private void procLogonResult(JSONObject result)
	{
		if (result == null)
		{
			ToastUtil.showMessage(MainActivity.this, R.string.logon_timeout);
			return;
		}

		try {
			int error = result.getInt("error");

			if (error == Const.ERROR_SUCCESS)
			{
				String info = result.getString("info");
				JSONObject jsonInfo = new JSONObject(info);
				//ToastUtil.showMessage(MainActivity.this, R.string.logon_ok);
				mGameView.setMyInfo(jsonInfo);

				if (result.has("username"))	// 表示是自动分配的用户名与密码
				{
					String username = result.getString("username");
					String passwd = result.getString("passwd");
					MyApp.saveUserInfo(username, passwd);
				}

				mStep = STEP_FIND_TABLE;
	            new ServerTask().execute();
			}
			else
			{
				ToastUtil.showMessage(MainActivity.this, R.string.logon_error);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	private void procFindTableResult(JSONObject result)
	{
		if (result == null)
		{
			return;
		}

		try {
			int error = result.getInt("error");

			if (error == Const.ERROR_SUCCESS)
			{
	            mGameView.setAllInfo(result);
				//ToastUtil.showMessage(MainActivity.this, R.string.find_table_ok);

				mStep = STEP_READY;
				mReadyView.setVisibility(View.VISIBLE);
			}
			else
			{
				ToastUtil.showMessage(MainActivity.this, R.string.find_table_fail);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	public void procRecvData(IoBuffer buf)
    {
    	int funcId = buf.getInt();

    	String txt = null;
    	byte[] data = new byte[buf.remaining()];
    	buf.get(data);
    	txt = new String(data);
    	JSONObject json = null;

		if (txt != null)
		{
			try
			{
				json = new JSONObject(txt);
			} catch (JSONException e) {
	            //e.printStackTrace();
	        }
		}

		try
		{
			switch (funcId)
			{
			case Const.FUNC_OTHER_PLAYER_ADD:
	        case Const.FUNC_OTHER_PLAYER_EXIT:
            case Const.FUNC_OTHER_PLAYER_READY:
				mGameView.procOtherPlayerChanged(funcId, json);
				break;

			default:
				break;
			}
		} catch (JSONException e) {
            e.printStackTrace();
        }
    }

	@Override
	public void onClick(View v) {
		switch (v.getId())
		{
		case R.id.btn_change_table:
			changeTable();
			break;

		case R.id.btn_start:
			readyPlay();
			break;

		default:
			break;
		}
	}

	private void changeTable()
	{

	}

	private void readyPlay()
	{
		mReadyView.setVisibility(View.GONE);
		mGameView.readyMe();
		mSocketClient.readyPlay();
	}
}
